<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" @click="handleCancel" v-if="permission.iqcBadHandling_cancel">撤 销</el-button>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button type="text" @click="view(row.id)" icon="el-icon-view" size="small" v-if="permission.iqcBadHanding_view">详情</el-button>
        <el-button type="text" @click="badHandling(row.id)" size="small" v-if="permission.iqcBadHanding_badHanding">不良处理</el-button>
      </template>
    </avue-crud>
    <el-dialog :key="timer" append-to-body :visible.sync="showDialog" width="60%" class="iqcDialog" @close="closeDialog" :fullscreen="fullscreenHandlingDialog">
      <div slot="title">
        填写不良处理结果<i
          class="el-dialog__close fill-screen-icon"
          :class="fullscreenHandlingDialog ? 'el-icon-news' : 'el-icon-full-screen'"
          @click="fullscreenHandlingDialog = !fullscreenHandlingDialog"
        ></i>
      </div>
      <avue-form ref="badhandlingProperties" v-model="model" :option="propertiesOption">
        <template slot="disposeTypeLabel">
          <span class="view-style">&nbsp;处理类型:</span>
        </template>
        <template slot="extractionQuantity">
          <el-input v-model="model.extractionQuantity" type="number" min="1" @input="changeValue" @keypress.native="keypressOverlimitRate" placeholder=""></el-input>
        </template>
        <template slot="receivingList">
          <div v-if="model.receivingList && model.receivingList.length > 0">
            <div v-for="(item, index) in model.receivingList" :key="index">
              <span style="font-size: 16px">{{ '收料记录' + (index + 1) }}：</span>
              <div class="demo-input-suffix input-content" style="margin: 0px 0px 10px 10px">
                收货数量：
                <el-input placeholder="收货数量" style="width: 200px; margin-right: 20px" disabled v-model="item.receiveQuantity" clearable> </el-input>
                <span class="must">特采数量：</span>
                <el-input placeholder="请输入特采数量" style="width: 200px" :disabled="badSequenceNumbers.length > 0" v-model="item.extractionQuantity" clearable> </el-input>
              </div>
              <div style="display: flex; flex-direction: row" v-if="item.inspectionObjectNgList && item.inspectionObjectNgList.length > 0">
                <label>不良包装条码：</label>
                <div style="max-height: 386px; overflow: hidden; overflow-y: scroll">
                  <table border="1">
                    <tr>
                      <th width="40" style="text-align: center">
                        <el-checkbox style="margin-right: 0" :indeterminate="item.isIndeterminate" @change="handleCheckAllChange($event, item.id)"></el-checkbox>
                      </th>
                      <th width="250" style="text-align: center">包装条码</th>
                      <th width="350" style="text-align: center">不良原因</th>
                    </tr>
                    <tr v-for="(badItem, index) in item.inspectionObjectNgList" :key="index">
                      <td style="text-align: center">
                        <el-checkbox style="margin-right: 0" v-model="badItem.checked" @change="handleCheckedChange($event, badItem.id, item.id)"></el-checkbox>
                      </td>
                      <td style="text-align: center">{{ badItem.objectSn }}</td>
                      <td style="text-align: center">{{ String(badItem.failureNameList) }}</td>
                    </tr>
                  </table>
                </div>
              </div>
            </div>
          </div>
          <div v-else></div>
        </template>
        <template slot="badInfo">
          <div style="display: flex; flex-direction: row">
            <label>不良包装条码：</label>
            <div style="max-height: 386px; overflow: hidden; overflow-y: scroll">
              <table border="1">
                <tr>
                  <!-- <th width="40" style="text-align: center" v-if="checkbox">
                    <el-checkbox style="margin-right: 0" :indeterminate="isIndeterminate" @change="handleCheckAllChange"></el-checkbox>
                  </th> -->
                  <th width="250" style="text-align: center">包装条码</th>
                  <th width="350" style="text-align: center">不良原因</th>
                </tr>
                <tr v-for="(item, index) in badSequenceNumbers" :key="index">
                  <td style="text-align: center" v-if="checkbox">
                    <el-checkbox style="margin-right: 0" v-model="item.checked"></el-checkbox>
                  </td>
                  <td style="text-align: center">{{ item.objectSn }}</td>
                  <td style="text-align: center">{{ String(item.failureNameList) }}</td>
                </tr>
              </table>
            </div>
          </div>
        </template>
        <template slot="attachmentLabel">
          <div>
            <label>
              <span style="color: #f56c6c" class="required text-danger">*</span>
              <span class="view-style">&nbsp;处理报告:</span>
              <span class="iqc-placeholder">&nbsp;（支持图片）</span>
            </label>
          </div>
        </template>
      </avue-form>
      <div slot="footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="submit" v-preventReClick>保存</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="cancel">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="详情" :key="timer" append-to-body :visible.sync="showViewDialog" width="60%" :fullscreen="fullscreenViewDialog" @close="cancelView">
      <div slot="title">
        详情<i
          class="el-dialog__close fill-screen-icon"
          :class="fullscreenViewDialog ? 'el-icon-news' : 'el-icon-full-screen'"
          @click="fullscreenViewDialog = !fullscreenViewDialog"
        ></i>
      </div>
      <avue-form ref="aplProperties" v-model="viewModel" :option="viewOption">
        <template slot="badInfo">
          <div style="display: flex; flex-direction: row">
            <label>不良包装条码：</label>
            <div style="max-height: 386px; overflow: hidden; overflow-y: scroll">
              <table border="1">
                <tr>
                  <th width="250" style="text-align: center">包装条码</th>
                  <th width="350" style="text-align: center">不良原因</th>
                </tr>
                <tr v-for="(item, index) in badSequenceNumbers" :key="index">
                  <td style="text-align: center">{{ item.objectSn }}</td>
                  <td style="text-align: center">{{ String(item.failureNameList) }}</td>
                </tr>
              </table>
            </div>
          </div>
        </template>
        <template slot="info" v-if="viewModel.attributeResultVOList && viewModel.attributeResultVOList.length > 0">
          <!-- <div v-if="viewModel.attributeResultVOList && viewModel.attributeResultVOList.length > 0"> -->
          <avue-form
            ref="itemProperties"
            v-for="(item, index) in viewModel.attributeResultVOList || []"
            v-model="viewModel.attributeResultVOList[index]"
            :option="itemOption"
            :key="index"
          >
            <template slot="info2">
              <span style="display: block">检验项： {{ item.item ? item.item.itemName : '' }}</span>
              <span style="display: block">检验明细项：{{ item.itemAttributeName }}</span>
              <span style="display: block">检验标准：{{ item.testCriterion }}</span>
              <span style="display: block">检验工具：{{ item.testTool }}</span>
              <div v-if="item.examineRealValue.type === 'SINGLE-INPUT'">
                <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2">
                  <label>{{ scanItem.label }}：</label>
                  <el-input style="width: 200px; margin-bottom: 5px" :value="scanItem.value" :disabled="true"> </el-input>
                </div>
              </div>
              <div v-if="item.examineRealValue.type === 'MULTIPLE-INPUT'">
                <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2" style="margin-bottom: 5px">
                  <label>{{ scanItem.label }}：</label>
                  <table border="1">
                    <tr>
                      <th width="50" style="text-align: center">次数</th>
                      <th width="70" style="text-align: center">测试值</th>
                      <th width="120" style="text-align: center">测试结果</th>
                      <th width="70" style="text-align: center">操作</th>
                    </tr>
                    <tr v-for="(result, index3) in item.examineRealValue.options[index2].valueResults" :key="index3">
                      <td style="text-align: center">{{ result.sequence }}</td>
                      <td style="text-align: center">{{ result.value }}</td>
                      <td style="text-align: center">
                        <span>{{ result.result }}</span>
                        <!-- <span style="margin-right: 2px"><input checked type="radio"/>OK</span> <span><input type="radio"/>NG</span> -->
                      </td>
                      <td style="text-align: center; color: red"><div>x</div></td>
                    </tr>
                  </table>
                </div>
              </div>
              <div v-if="item.examineRealValue.type === 'RADIO'">
                <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2">
                  <label>{{ scanItem.label }}：</label>
                  <el-radio v-model="scanItem.valueResults" disabled :label="scanItem.realLabel">{{ scanItem.realLabel }}</el-radio>
                  <el-radio v-model="scanItem.valueResults" disabled :label="scanItem.shamLabel">{{ scanItem.shamLabel }}</el-radio>
                </div>
              </div>
              <div v-if="item.examineRealValue.type === 'SCAN'">
                <div v-for="(scanItem, index2) in item.examineRealValue.options" :key="index2">
                  <label>{{ scanItem.label + '数量' }}：</label>
                  <el-input style="width: 200px" :value="item.examineRealValue.scanContent.length" :disabled="true"> </el-input>
                </div>
              </div>
            </template>
          </avue-form>
          <!-- </div> -->
        </template>
        <template slot="info" v-else>
          <span></span>
        </template>
        <template slot="attachments">
          <div>
            <div style="display: inline-block; text-align: center" v-for="(item, index) in viewModel.attachments" :key="item.attachmentId">
              <el-image style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="item.link" @click="openPreview(index, item.link)"></el-image>
              <!-- <el-button type="text" v-if="item.link" icon="el-icon-download" size="small" @click="handleDownload(item)">下载 </el-button> -->
            </div>
          </div>
        </template>
      </avue-form>
      <!-- <avue-form ref="properties" v-model="viewModel" :option="viewOption">
        <template slot="examineResultLabel">
          <span>&nbsp;IQC检验结果:</span>
        </template>

        <template slot="attachments">
          <div>
            <div style="display: inline-block; text-align: center" v-for="(item, index) in viewModel.attachments" :key="item.attachmentId">
              <el-image style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="item.link" @click="openPreview(index, item.link)"></el-image>
              <el-button type="text" v-if="item.link" icon="el-icon-download" size="small" @click="handleDownload(item)">下载 </el-button>
            </div>
          </div>
        </template>
        <template slot="disposeRemarkLabel">
          <span class="view-style">&nbsp;备注:</span>
        </template>
      </avue-form> -->
    </el-dialog>
  </basic-container>
</template>

<script>
import { getList, getDetail, inspect, cancel } from '@/api/quality/iqc-examine';
import { mapGetters } from 'vuex';
import index from '../../components/chart/index.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';

export default {
  components: {
    index,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'IQC_BAD_HANDING',
      form: {},
      model: {
        receivingList: [
          {
            receiveQuantity: 0,
            extractionQuantity: 0
          }
        ]
      },
      timer: new Date().getTime(),
      isIndeterminate: false,
      viewModel: {},
      attachments: [],
      query: { status: 2 },
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      data: [],
      selectData: [],
      badSequenceNumbers: [],
      code: '00',
      checkIqc: true,
      checkbox: false,
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        delBtn: false,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 120,
        menuWidth: 100,
        searchLabelWidth: 90,
        searchMenuSpan: 3,
        searchMenuPosition: 'right',
        menuWidth: 200,
        columnBtn: false,
        column: [
          {
            label: '检验单号',
            prop: 'documentNo',
            search: true,
            searchOrder: 1,
            searchSpan: 5,
            order: 1,
            rules: [
              {
                required: true,
                message: '请输入检验单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料编码',
            prop: 'partNo',
            searchOrder: 1,
            search: true,
            searchSpan: 5,
            order: 2,
            rules: [
              {
                required: true,
                message: '请输入物料编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料名称',
            prop: 'partName',
            searchOrder: 2,
            order: 3,
            rules: [
              {
                required: true,
                message: '请输入物料名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '制单人',
            prop: 'creator'
          },
          // {
          //   label: '物料批次',
          //   prop: 'lotNo',
          //   order: 4,
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入物料批次',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '供应商代码',
            prop: 'partnerCode',
            search: true,
            searchSpan: 5,
            order: 5,
            rules: [
              {
                required: true,
                message: '请输入供应商代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '送检数量',
            prop: 'sendExamineQuantity',
            order: 7,
            rules: [
              {
                required: true,
                message: '请输入送检数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验方式',
            prop: 'examineMode',
            order: 8,
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=inspection_mode',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请输入检验方式',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '检验日期',
            prop: 'examineDate',
            search: true,
            searchOrder: 20,
            searchSpan: 6,
            type: 'date',
            searchType: 'daterange',
            order: 18,
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
          },
          {
            label: '检验人',
            prop: 'examineByName'
          }
        ]
      },
      showDialog: false, //IQC检验结果模态框
      fullscreenHandlingDialog: false,
      showViewDialog: false,
      fullscreenViewDialog: false,
      propertiesOption: {
        emptyBtn: false,
        submitBtn: false,
        column: [
          {
            label: '处理类型',
            prop: 'disposeType',
            labelWidth: '100',
            span: 20,
            require: true,
            type: 'radio',
            value: 'FULLRETURN',
            dicData: [
              {
                label: '批量退货',
                value: 'FULLRETURN'
              },
              {
                label: '让步收料',
                value: 'DEVIATION'
              },
              {
                label: '部分特采',
                value: 'EXTRACTION'
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择处理类型',
                trigger: 'blur'
              }
            ],
            control: (val, form) => {
              let that = this;
              if (val == 'FULLRETURN') {
                that.model.returnOrSpecialQuantity = that.model.sendExamineQuantity;
                that.model.extractionQuantity = '';
                return {
                  returnOrSpecialQuantity: { display: true, label: '退货数量' },
                  extractionQuantity: { display: false },
                  receivingList: { display: false },
                  badInfo: { display: true }
                };
              } else if (val == 'DEVIATION') {
                that.model.returnOrSpecialQuantity = that.model.sendExamineQuantity;
                // that.model.extractionQuantity = '';
                // that.checkbox = false;
                return {
                  returnOrSpecialQuantity: { display: true, label: '特采数量' },
                  extractionQuantity: { display: false },
                  receivingList: { display: false },
                  badInfo: { display: true }
                };
              } else if (val == 'EXTRACTION') {
                return {
                  returnOrSpecialQuantity: { display: false },
                  extractionQuantity: { display: false },
                  receivingList: { display: true },
                  badInfo: { display: false }
                };
              }
            }
          },
          {
            label: '检验单号',
            prop: 'documentNo',
            span: 6,
            disabled: true
          },
          {
            label: '物料编码',
            prop: 'partNo',
            span: 6,
            disabled: true
          },
          {
            label: '收货数量',
            prop: 'sendExamineQuantity',
            span: 6,
            disabled: true
          },
          {
            label: '退货数量',
            prop: 'returnOrSpecialQuantity',
            span: 6,
            disabled: true
          },
          {
            label: '特采数量',
            formslot: true,
            prop: 'extractionQuantity',
            span: 6,
            rules: [
              {
                required: true,
                message: '请输入特采数量',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '',
            prop: 'badInfo',
            labelWidth: '0',
            formslot: true,
            display: false,
            row: true,
            span: 20
          },
          {
            label: '',
            labelWidth: '0',
            prop: 'receivingList',
            formslot: true,
            display: false,
            span: 20
          },
          {
            label: '',
            labelWidth: '40',
            prop: 'attachmentLabel',
            require: true,
            formslot: true
          },
          {
            label: '',
            prop: 'iqcNGAttachments',
            type: 'upload',
            span: 20,
            loadText: '图片上传中，请稍等',
            propsHttp: {
              url: 'link',
              name: 'attachId',
              res: 'data'
            },
            listType: 'picture',
            limit: 3,
            accept: 'image/png, image/jpeg, image/jpg',
            tip: '只能上传png/jpeg/jpg文件',
            action: '/api/blade-resource/oss/endpoint/put-file-attach',
            rules: [
              {
                required: true,
                message: '请上传IQC检验报告',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注/原因',
            prop: 'disposeRemark',
            span: 20,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            rules: [
              {
                message: '请填写备注/原因',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      viewOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: '160',
        column: [
          {
            label: '严重',
            prop: 'severityCode',
            span: 8,
            disabled: true,
            control: (val, form) => {
              switch (val) {
                case 'NORMAL':
                  this.viewModel.severityCode = '正常';
                  break;
                case 'REDUCE':
                  this.viewModel.severityCode = '加宽';
                  break;
                case 'TIGHTEH':
                  this.viewModel.severityCode = '加严';
                  break;
                default:
                  break;
              }
            }
          },
          {
            label: '检验水平',
            prop: 'levelType',
            span: 8,
            disabled: true
          },
          {
            label: '检验水平代码',
            prop: 'levelCode',
            span: 8,
            disabled: true
          },
          {
            label: '质量质量水平',
            prop: 'limitValue',
            span: 8,
            disabled: true
          },
          {
            label: '检验数量',
            prop: 'examineQuantity',
            span: 8,
            disabled: true
          },
          {
            label: '抽检数量',
            prop: 'samplingQuantity',
            span: 8,
            disabled: true
          },
          {
            label: 'Ac',
            prop: 'acQuantity',
            span: 8,
            disabled: true
          },
          {
            label: 'Re',
            prop: 'reQuantity',
            span: 8,
            disabled: true
          },
          {
            labelWidth: 60,
            label: '',
            prop: 'badInfo',
            span: 24
          },
          {
            labelWidth: 60,
            label: '',
            prop: 'info',
            span: 24
          },
          {
            label: '不良总量',
            prop: 'ngQuantity',
            span: 8,
            disabled: true,
            row: true
          },
          {
            label: '综合判定结果',
            prop: 'examineResult',
            type: 'radio',
            span: 24,
            disabled: true,
            labelWidth: 100,
            row: true,
            dicData: [
              {
                label: 'OK',
                value: 'OK'
              },
              {
                label: 'NG',
                value: 'NG'
              }
            ]
          },
          {
            label: '附件',
            prop: 'attachments',
            listType: 'picture',
            type: 'upload',
            span: 24,
            disabled: true
          },
          {
            label: '备注/原因',
            prop: 'remark',
            span: 20,
            type: 'textarea',
            maxRows: 3,
            minRows: 3,
            disabled: true,
            row: true
          }
        ]
      },
      itemOption: {
        emptyBtn: false,
        submitBtn: false,
        labelWidth: '160',
        column: [
          {
            labelWidth: 60,
            label: '',
            prop: 'info2',
            span: 24,
            hide: true
          },
          {
            label: '检验结果',
            prop: 'examineResult',
            type: 'radio',
            span: 24,
            disabled: true,
            labelWidth: 100,
            row: true,
            formslot: true,
            dicData: [
              {
                label: 'OK',
                value: 'OK'
              },
              {
                label: 'NG',
                value: 'NG'
              }
            ]
          },
          {
            label: 'CRI（严重问题）数',
            prop: 'criQuantity',
            span: 8,
            disabled: true
          },
          {
            label: 'MAJ（主要问题）数',
            prop: 'majQuantity',
            span: 8,
            disabled: true
          },
          {
            label: 'MIN（次要问题）数',
            prop: 'minQuantity',
            span: 8,
            disabled: true
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {};
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    /**
     * 提交检验结果
     */
    async submit() {
      // this.model.extFields = null;
      let attribute = this.model;
      if (attribute.disposeType !== 'EXTRACTION') {
        attribute.inspectionObjectNgList = this.badSequenceNumbers;
      } else {
        let inspectionObjectNgList = [];
        attribute.inspectionObjectNgList = this._forEach(this.model.receivingList, (item) => {
          if (item.inspectionObjectNgList && item.inspectionObjectNgList.length > 0) {
            inspectionObjectNgList.push(...item.inspectionObjectNgList);
          }
        });
        attribute.inspectionObjectNgList = inspectionObjectNgList.filter((item) => item.checked);
        attribute.extractionQuantity = this.model.receivingList.reduce((prev, cur) => {
          return prev + Number(cur.extractionQuantity);
        }, 0);
      }
      let done;
      let flag;
      if (this.model.receivingList && this.model.receivingList.length > 0) {
        flag = this.model.receivingList.some((item) => {
          return item.extractionQuantity == null || item.extractionQuantity == undefined || item.extractionQuantity == '';
        });
      }

      if (attribute.disposeType === 'EXTRACTION' && flag) {
        this.$message({
          type: 'warning',
          message: '特采数量为必填项，请输入!'
        });
        return;
      }

      let extractionQuantity = this.model.receivingList.reduce((prev, cur) => {
        return prev + Number(cur.extractionQuantity);
      }, 0);

      let receiveQuantity = this.model.receivingList.reduce((prev, cur) => {
        return prev + Number(cur.receiveQuantity);
      }, 0);

      if (attribute.disposeType === 'EXTRACTION' && extractionQuantity > receiveQuantity) {
        this.$message({
          type: 'warning',
          message: '特采数量不可超过收货数量!'
        });
        return;
      }
      let validDate = await new Promise((resolve, reject) => {
        this.$refs.badhandlingProperties.validate((valid, done) => {
          done = done;
          if (valid) {
            resolve();
            done();
          } else {
          }
        });
      });

      Promise.all([validDate]).then(() => {
        attribute.status = 3;
        if (attribute.disposeType === 'EXTRACTION') {
          //特采
          attribute.disposeQuantity = attribute.extractionQuantity;
        } else if (attribute.disposeType === 'DEVIATION') {
          //让步
          attribute.extractionQuantity = attribute.sendExamineQuantity;
          attribute.disposeQuantity = attribute.sendExamineQuantity;
        } else {
          //批量
          attribute.disposeQuantity = 0;
          attribute.extractionQuantity = 0;
        }
        // attribute.disposeType != 'EXTRACTION' ? (attribute.disposeQuantity = attribute.sendExamineQuantity) : (attribute.disposeQuantity = attribute.extractionQuantity);
        let attachments = attribute.iqcNGAttachments.map((attachment) => {
          return {
            link: attachment.value,
            attachmentId: attachment.label,
            attachmentType: 'NG'
          };
        });
        //合并待检上传的图片
        attribute.attachments = attribute.attachments.concat(attachments);
        inspect(attribute).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
            this.$refs.badhandlingProperties.resetForm();
            this.showDialog = false;
          },
          (error) => {
            window.console.log(error);
          }
        );
        done();
      });
    },

    //只能输入正整数
    changeValue(value) {
      if (this.model.extractionQuantity.length == 1) {
        value = value.replace(/[^1-9.]/g, '');
      } else {
        value.replace(/\D/g, '');
      }
      this.model.extractionQuantity = value;
      return value;
    },
    //限制不能输入小数点
    keypressOverlimitRate(e) {
      let code = e.keyCode;
      if (code === 46) {
        e.preventDefault();
      }
    },

    cancel() {
      this.showDialog = false;
      this.model = {};
    },
    cancelView() {
      this.showViewDialog = false;
      this.viewModel = {};
      this.attachments = [];
    },

    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = { status: 2 };
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.examineDate && params.examineDate.length > 0) {
        params.startExamineDate = params.examineDate[0];
        params.endExamineDate = params.examineDate[1];
        // let startExamineDate = new Date(params.examineDate[0]);
        // startExamineDate.setHours(0, 0, 0);
        // let endExamineDate = new Date(params.examineDate[1]);
        // endExamineDate.setHours(23, 59, 59);
        // params.startExamineDate = this.$moment(startExamineDate).format('YYYY-MM-DD  HH:mm:ss');
        // params.endExamineDate = this.$moment(endExamineDate).format('YYYY-MM-DD  HH:mm:ss');
      }
      delete params.examineDate;
      params.status = 2;
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      params.documentType = 'IQC';
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        // [] || dataListTable
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    // badSequenceNumberHandling(list = []) {
    //   let badSequenceNumbers = [];
    //   this._forEach(list, (item) => {
    //     item.examineRealValue = JSON.parse(item.examineRealValue);
    //     let criList = this.handleFailureName(item.criList, item.failureName, item.failureCode);
    //     let majList = this.handleFailureName(item.majList, item.failureName, item.failureCode);
    //     let minList = this.handleFailureName(item.minList, item.failureName, item.failureCode);
    //     item.attributeBadSequenceNumbers = [...criList, ...majList, ...minList];
    //     badSequenceNumbers = badSequenceNumbers.concat(item.attributeBadSequenceNumbers);
    //   });

    //   badSequenceNumbers = this._uniqWith(badSequenceNumbers, (arrVal, othVal) => {
    //     if (arrVal.objectSn === othVal.objectSn) {
    //       let failureNames = [];
    //       let arrVals = [];
    //       let othVals = [];
    //       if (arrVal.failureName && arrVal.failureName.includes(',')) {
    //         arrVals = arrVal.failureName.split(',');
    //       } else if (arrVal.failureName) {
    //         failureNames.push(arrVal.failureName);
    //       }
    //       if (othVal.failureName && othVal.failureName.includes(',')) {
    //         othVals = othVal.failureName.split(',');
    //       } else if (othVal.failureName) {
    //         failureNames.push(othVal.failureName);
    //       }
    //       failureNames = this._uniq(failureNames.concat([...arrVals, ...othVals]));
    //       arrVal.failureName = failureNames.join(',');
    //       othVal.failureName = failureNames.join(',');
    //     }
    //     return arrVal.objectSn === othVal.objectSn;
    //   });
    //   return badSequenceNumbers;
    // },
    //不良处理
    async badHandling(id) {
      this.newKey();
      this.model = {};
      this.showDialog = true;
      this.fullscreenHandlingDialog = false;
      this.badSequenceNumbers = [];
      getDetail(id).then((res) => {
        let data = res.data.data;
        if (!this._get(data, 'examineResult', '')) {
          data.examineResult = 'OK';
        }
        this.model = {
          ...data,
          disposeType: 'FULLRETURN'
        };
        this.model.receivingList = this.model.receivingVOs || [];
        this._forEach(this.model.receivingList, (item) => {
          item.isIndeterminate = false;
          if (item.inspectionObjectNgList && item.inspectionObjectNgList.length > 0) {
            this.badSequenceNumbers.push(...item.inspectionObjectNgList);
          }
          this._forEach(item.inspectionObjectNgList, (badItem) => {
            badItem.checked = false;
          });
          if (item.inspectionObjectNgList && item.inspectionObjectNgList.length > 0) {
            let extractionQuantity = item.inspectionObjectNgList.reduce((prev, cur) => {
              return prev + Number(cur.objectQuantity);
            }, 0);
            item.extractionQuantity = Number(item.receiveQuantity) - Number(extractionQuantity);
          }
        });

        this.model.returnOrSpecialQuantity = this.model.sendExamineQuantity;

        this._forEach(this.badSequenceNumbers, (item) => {
          item.checked = false;
        });
        this.badSequenceNumbers = this._cloneDeep(this.badSequenceNumbers);

        // let badInfoColumn = this.findObject(this.propertiesOption.column, 'badInfo');
        // if (this.badSequenceNumbers.length > 0) {
        //   badInfoColumn.display = true;
        // } else {
        //   badInfoColumn.display = false;
        // }
        // console.log(this.badSequenceNumbers.length, badInfoColumn, 333);
      });
    },
    newKey() {
      this.timer = new Date().getTime();
    },
    // handleCheckAllChange(val) {
    //   this.badSequenceNumbers = this.badSequenceNumbers.map((item) => {
    //     if (val) {
    //       item.checked = true;
    //     } else {
    //       item.checked = false;
    //     }
    //     return item;
    //   });
    //   this.isIndeterminate = false;
    // },
    handleCheckAllChange(val, id) {
      this.model.receivingList = this.model.receivingList.map((item) => {
        if (item.id === id) {
          item.inspectionObjectNgList = item.inspectionObjectNgList.map((badItem) => {
            if (val) {
              if (!item.isIndeterminate) {
                badItem.checked = true;
                item.extractionQuantity = Number(item.extractionQuantity) + Number(badItem.objectQuantity);
              }
            } else {
              if (!item.isIndeterminate) {
                badItem.checked = false;
                item.extractionQuantity = Number(item.extractionQuantity) - Number(badItem.objectQuantity);
              }
            }
            badItem.isIndeterminate = item.inspectionObjectNgList.some((badItem2) => badItem2.checked);
            return badItem;
          });
        }
        return item;
      });
    },
    // handleCheckedChange(id) {
    //   this.isIndeterminate = this.badSequenceNumbers.some((item) => item.checked);
    // },
    handleCheckedChange(val, itemId, id) {
      this.model.receivingList = this.model.receivingList.map((item) => {
        if (item.id === id) {
          item.inspectionObjectNgList = item.inspectionObjectNgList.map((badItem) => {
            if (badItem.id === itemId) {
              badItem.checked = val;
              if (badItem.checked) {
                item.extractionQuantity = Number(item.extractionQuantity) + Number(badItem.objectQuantity);
              } else {
                item.extractionQuantity = Number(item.extractionQuantity) - Number(badItem.objectQuantity);
              }
            }
            return badItem;
          });
          item.isIndeterminate = item.inspectionObjectNgList.some((badItem2) => badItem2.checked);
        }
        return item;
      });
    },
    async view(id) {
      this.newKey();
      this.viewModel = {};
      this.showViewDialog = true;
      this.fullscreenViewDialog = false;
      this.badSequenceNumbers = [];
      getDetail(id).then((res) => {
        this.viewModel = res.data.data;
        this._forEach(this.viewModel.receivingList, (item) => {
          if (item.inspectionObjectNgList && item.inspectionObjectNgList.length > 0) {
            this.badSequenceNumbers.push(...item.inspectionObjectNgList);
          }
        });
        this.badSequenceNumbers = this._cloneDeep(this.badSequenceNumbers);
        // let badInfoColumn = this.findObject(this.viewOption.column, 'badInfo');
        // if (this.badSequenceNumbers.length > 0) {
        //   badInfoColumn.display = true;
        // } else {
        //   badInfoColumn.display = false;
        // }
        console.log(this.badSequenceNumbers.length, badInfoColumn, 333);
      });
    },
    closeDialog() {
      this.$refs.badhandlingProperties.resetForm();
    },
    handleDownload(item) {
      window.open(`${item.link}`);
    },

    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    handleCancel() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择一条数据');
        return;
      }
      if (this.selectionList.length > 1) {
        this.$message.warning('只能选择一条数据');
        return;
      }
      this.$confirm('撤销后，检验记录及报表将同步撤销！', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return cancel({
            id: this.ids
          });
        })
        .then(() => {
          // 刷新表格数据并重载
          this.data = [];
          this.$refs.crud.refreshTable();
          this.$refs.crud.toggleSelection();
          // 表格数据重载
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    }
  }
};
</script>

<style scoped lang="scss">
$size: 16px;
.view-style {
  font-weight: bold;
  font-size: $size;
}
.iqc-placeholder {
  font-size: $size;
  color: #aaaaaa;
}

.iqcDialog {
  ::v-deep input[type='file'] {
    display: none !important;
  }
}
$BORDER-STYLE: 1px solid #f0f0f0 !important;
::v-deep .inspection-btn:hover {
  background-color: #dedede;
}
::v-deep .el-dialog__header {
  border-bottom: $BORDER-STYLE;
}

::v-deep .el-dialog__footer {
  border-top: $BORDER-STYLE;
}

.fill-screen-icon {
  color: #909399;
  font-size: 15px;
  float: right;
  padding-right: 25px;
  &:hover {
    color: #409eff;
  }
}

.group-title {
  border-bottom: 1px solid rgb(240, 240, 240) !important;
  font-size: 16px;
  font-weight: 500;
  height: 50px;
  line-height: 50px;
  color: rgba(0, 0, 0, 0.85);
  margin-bottom: 20px;
}
.input-content {
  display: flex;
  flex-direction: row;
}
.must::before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
</style>
